﻿namespace Nomo.CoreModule
{
    /// <summary>
    /// 为 <see cref="string"/> 类的实例提供扩展方法。
    /// </summary>
    public static class StringExtension
    {
        /// <summary>
        /// 去掉所有空白字符。
        /// </summary>
        /// <returns></returns>
        public static string WithoutWhiteSpaces(this string value)
        {
            return !string.IsNullOrEmpty(value) ? WithoutSpacesInternal(value) : value;
        }

        private static unsafe string WithoutSpacesInternal(string value)
        {
            var length      = value.Length;
            var newChars    = stackalloc char[length];
            var currentChar = newChars;
            for (var i = 0; i < length; i++)
            {
                var ch = value[i];
                switch (ch)
                {
                    case '\u0009':
                    case '\u000A':
                    case '\u000B':
                    case '\u000C':
                    case '\u000D':
                    case '\u0020':
                    case '\u0085':
                    case '\u00A0':
                        continue;
                    default:
                        *currentChar++ = ch;
                        break;
                }
            }

            return new string(newChars, 0, (int) (currentChar - newChars));
        }

        /// <summary>
        /// 无中断空格的。
        /// </summary>
        /// <returns></returns>
        public static string NonBreakingSpaced(this string value)
        {
            return !string.IsNullOrEmpty(value) ? NonBreakingSpacedInternal(value) : value;
        }

        private static unsafe string NonBreakingSpacedInternal(string value)
        {
            var length = value.Length;
            var index  = length;

            fixed (char* ptr = value)
            {
                while (--index >= 0)
                {
                    if (ptr[index] == '\u0020')
                    {
                        ptr[index] = '\u00A0';
                    }
                }
                return new string(ptr, 0, length);
            }
        }
    }
}
